package dictionary

import (
	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/bi/database"

	"strconv"

	"github.com/go-redis/redis"
	log "github.com/sirupsen/logrus"
)

//Department 部门
type Department struct {
	redisCli *redis.Client
	hkey     string
}

//NewDepartment 新建部门对象
func NewDepartment() (d *Department) {
	d = &Department{
		redisCli: base.RedisClients[0],
		hkey:     "department",
	}
	return
}

//Build 构建
func (d *Department) Build() error {
	log.Info("开始构建部门")
	dl := database.DefaultDataLoader
	sql := "select ID,OrganName from T_Organization"
	rows, err := dl.LoadDataBySQL(sql)
	if err != nil {
		return err
	}
	defer rows.Close()
	for rows.Next() {
		var id int
		var name string
		err := rows.Scan(&id, &name)
		if err != nil {
			return err
		}
		if err := d.addData(id, name); err != nil {
			return err
		}
	}
	log.Info("构建部门完成")
	return nil
}
func (d *Department) addData(id int, name string) error {
	if err := d.redisCli.HSet(d.hkey, strconv.Itoa(id), name).Err(); err != nil {
		return err
	}
	return nil
}

//GetNameByID 根据ID获取Name
func (d *Department) GetNameByID(id int) (string, error) {
	name, err := d.redisCli.HGet(d.hkey, strconv.Itoa(id)).Result()
	if err != nil {
		return "", err
	}
	return name, nil
}
